package com.eastfair.venuebooking.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eastfair.annotation.annotation.log.SysLog;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.dto.UserAccountDto;
import com.eastfair.auth.entity.Organization;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.entity.SuperEntity;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.venuebooking.entity.ExhibitionResponsibilityer;
import com.eastfair.venuebooking.dto.ExhibitionResponsibilityerSaveDTO;
import com.eastfair.venuebooking.dto.ExhibitionResponsibilityerUpdateDTO;
import com.eastfair.venuebooking.dto.ExhibitionResponsibilityerPageQuery;
import com.eastfair.venuebooking.enumeration.ResponsibilityerRoleEnum;
import com.eastfair.venuebooking.exceptioncode.VenueBookingExceptionCode;
import com.eastfair.venuebooking.service.ExhibitionResponsibilityerService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import com.eastfair.boot.controller.SuperController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.echo.core.EchoService;
import com.eastfair.core.base.R;
import com.eastfair.venuebooking.vo.ExhibitionResponsibilityerVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eastfair.boot.request.PageParams;
import com.eastfair.core.context.ContextUtil;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;


/**
 * <p>
 * 前端控制器
 * 展会负责人
 * </p>
 *
 * @author linan
 * @date 2022-06-08
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/exhibitionResponsibilityer")
@Api(value = "ExhibitionResponsibilityer", tags = "展会负责人")
@PreAuth(replace = "venuebooking:exhibitionResponsibilityer:")
public class ExhibitionResponsibilityerController extends SuperController<ExhibitionResponsibilityerService, Long, ExhibitionResponsibilityer, ExhibitionResponsibilityerPageQuery, ExhibitionResponsibilityerSaveDTO, ExhibitionResponsibilityerUpdateDTO> {

    @Autowired
    private EchoService echoService;
    @Autowired
    private UserAccountServiceFeign userAccountServiceFeign;

    @Override
    public void handlerResult(IPage<ExhibitionResponsibilityer> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<ExhibitionResponsibilityer> exhibitionResponsibilityerList = list.stream().map((map) -> {
            ExhibitionResponsibilityer exhibitionResponsibilityer = ExhibitionResponsibilityer.builder().build();
            //TODO 请在这里完成转换
            return exhibitionResponsibilityer;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(exhibitionResponsibilityerList));
    }



    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<ExhibitionResponsibilityerPageQuery> params) {
        ExhibitionResponsibilityerPageQuery pageQuery = params.getModel();
        //分页处理
        if(ContextUtil.getProjectId()!=null){
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 获取成员列表
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取成员列表", notes = "获取成员列表")
    @GetMapping("/getExhibitionResponsibilityerList")
    public R<List<ExhibitionResponsibilityerVO>> getExhibitionResponsibilityerList(@RequestParam("exhibitionId") @Validated @NotNull(message = "展会ID必填")  Long exhibitionId) {
        log.info("getExhibitionResponsibilityerList - 获取成员列表   exhibitionId: {}",exhibitionId);
        QueryWrapper<ExhibitionResponsibilityer> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ExhibitionResponsibilityer::getExhibitionId,exhibitionId).eq(ExhibitionResponsibilityer::getIsDeleted, BusinessConstant.NO);
        List<ExhibitionResponsibilityer> list = baseService.list(wrapper);
        List<ExhibitionResponsibilityerVO> exhibitionResponsibilityers = ConvertUtil.convertList(list, ExhibitionResponsibilityerVO.class);
        Map<String, String> userOrgMap = new HashMap<>(8);
        if(CollectionUtils.isNotEmpty(list)){
            try{
                UserAccountDto userAccountDto = new UserAccountDto();
                userAccountDto.setUserIds(list.stream().map(ExhibitionResponsibilityer::getUserId).collect(Collectors.toList()));
                R<List<UserAccountVo>> listR = userAccountServiceFeign.querySimpleByIds(userAccountDto);
                if(CollectionUtils.isNotEmpty(listR.getData()) ){
                    listR.getData().forEach(e->{
                        if(CollectionUtils.isNotEmpty(e.getOrganizationList())){
                            for (Organization organization : e.getOrganizationList()) {
                                userOrgMap.put(e.getId()+"_"+organization.getId(),organization.getName());
                            }
                        }
                    });
                }else {
                    log.warn("用户信息查询为空 {}",list.stream().map(SuperEntity::getCreatedBy).collect(Collectors.toList()));
                }
            }catch (Exception e){
                log.error("用户信息查询失败",e);
            }
        }
        for (ExhibitionResponsibilityerVO exhibitionResponsibilityerVO : exhibitionResponsibilityers) {
            exhibitionResponsibilityerVO.setOrgName(userOrgMap.get(exhibitionResponsibilityerVO.getUserId()+"_"+exhibitionResponsibilityerVO.getOrgId()));
        }
        return R.success(exhibitionResponsibilityers);
    }

    /**
     * 删除展会成员
     *
     * @param id 成员列表ID
     * @return R
     */
    @ApiOperation(value = "删除展会成员", notes = "删除展会成员")
    @SysLog("删除展会成员")
    @GetMapping("/removeExhibitionResponsibilityer")
    public R removeExhibitionResponsibilityer(@RequestParam("id") @Validated @NotNull(message = "成员列表ID必填")  Long id) {
        log.info("getExhibitionResponsibilityerList - 删除展会成员   id: {}",id);
        ExhibitionResponsibilityer responsibilityer = baseService.getById(id);
        if(Objects.isNull(responsibilityer)){
            return R.fail(VenueBookingExceptionCode.RE_NOT_FIND.getMsg());
        } else if(responsibilityer.getResponsibilityerRole().equals(ResponsibilityerRoleEnum.MAIN_IN_CHARGE.getValue())){
            return R.fail(VenueBookingExceptionCode.RE_CANT_REMOVE.getMsg());
        }  else {
            return R.success(baseService.updateById(ExhibitionResponsibilityer.builder().id(id).isDeleted(BusinessConstant.YES).build()));
        }
    }

}
